package com.robotic.sensor.controller;

import java.util.List;
import java.util.Date;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.robotic.common.annotation.Log;
import com.robotic.common.core.controller.BaseController;
import com.robotic.common.core.domain.AjaxResult;
import com.robotic.common.enums.BusinessType;
import com.robotic.common.utils.poi.ExcelUtil;
import com.robotic.common.core.page.TableDataInfo;
import com.robotic.common.utils.DateUtils;
import com.robotic.sensor.domain.SensorData;
import com.robotic.sensor.service.ISensorDataService;

/**
 * 传感器数据Controller
 * 
 * @author robotic
 * @date 2024-01-20
 */
@RestController
@RequestMapping("/sensor/data")
public class SensorDataController extends BaseController
{
    @Autowired
    private ISensorDataService sensorDataService;

    /**
     * 查询传感器数据列表
     */
    @PreAuthorize("@ss.hasPermi('sensor:data:list')")
    @GetMapping("/list")
    public TableDataInfo list(SensorData sensorData)
    {
        startPage();
        List<SensorData> list = sensorDataService.selectSensorDataList(sensorData);
        return getDataTable(list);
    }

    /**
     * 根据区域代码查询传感器数据
     */
    @GetMapping("/region/{regionCode}")
    public AjaxResult getByRegionCode(@PathVariable("regionCode") String regionCode)
    {
        List<SensorData> list = sensorDataService.selectSensorDataByRegionCode(regionCode);
        return AjaxResult.success(list);
    }

    /**
     * 根据传感器类型查询传感器数据
     */
    @GetMapping("/sensor/{sensorType}")
    public AjaxResult getBySensorType(@PathVariable("sensorType") String sensorType)
    {
        List<SensorData> list = sensorDataService.selectSensorDataBySensorType(sensorType);
        return AjaxResult.success(list);
    }

    /**
     * 根据机器人ID查询传感器数据
     */
    @GetMapping("/robot/{robotId}")
    public AjaxResult getByRobotId(@PathVariable("robotId") String robotId)
    {
        List<SensorData> list = sensorDataService.selectSensorDataByRobotId(robotId);
        return AjaxResult.success(list);
    }

    /**
     * 根据任务ID查询传感器数据
     */
    @GetMapping("/task/{taskId}")
    public AjaxResult getByTaskId(@PathVariable("taskId") String taskId)
    {
        List<SensorData> list = sensorDataService.selectSensorDataByTaskId(taskId);
        return AjaxResult.success(list);
    }

    /**
     * 查询异常传感器数据（非标准数据）
     */
    @GetMapping("/abnormal")
    public AjaxResult getAbnormalData(@RequestParam(required = false) String regionCode, 
                                     @RequestParam(required = false) String sensorType)
    {
        List<SensorData> list = sensorDataService.selectAbnormalSensorData(regionCode, sensorType);
        return AjaxResult.success(list);
    }

    /**
     * 查询未处理的异常传感器数据
     */
    @GetMapping("/unhandled")
    public AjaxResult getUnhandledAbnormalData()
    {
        List<SensorData> list = sensorDataService.selectUnhandledAbnormalSensorData();
        return AjaxResult.success(list);
    }

    /**
     * 查询危险级别的传感器数据
     */
    @GetMapping("/danger")
    public AjaxResult getDangerData(@RequestParam(required = false) String regionCode, 
                                   @RequestParam(required = false) String sensorType)
    {
        List<SensorData> list = sensorDataService.selectDangerSensorData(regionCode, sensorType);
        return AjaxResult.success(list);
    }

    /**
     * 根据时间范围查询传感器数据
     */
    @GetMapping("/timeRange")
    public AjaxResult getByTimeRange(@RequestParam String startTime, 
                                    @RequestParam String endTime,
                                    @RequestParam(required = false) String regionCode,
                                    @RequestParam(required = false) String sensorType)
    {
        Date start = DateUtils.parseDate(startTime);
        Date end = DateUtils.parseDate(endTime);
        List<SensorData> list = sensorDataService.selectSensorDataByTimeRange(start, end, regionCode, sensorType);
        return AjaxResult.success(list);
    }

    /**
     * 查询最新的传感器数据
     */
    @GetMapping("/latest")
    public AjaxResult getLatestData(@RequestParam String regionCode, 
                                   @RequestParam String sensorType,
                                   @RequestParam(defaultValue = "10") Integer limit)
    {
        List<SensorData> list = sensorDataService.selectLatestSensorData(regionCode, sensorType, limit);
        return AjaxResult.success(list);
    }

    /**
     * 统计传感器数据数量
     */
    @GetMapping("/count")
    public AjaxResult countData(@RequestParam(required = false) String regionCode, 
                               @RequestParam(required = false) String sensorType,
                               @RequestParam(required = false) String detectStatus)
    {
        Long count = sensorDataService.countSensorData(regionCode, sensorType, detectStatus);
        return AjaxResult.success(count);
    }

    /**
     * 获取传感器数据统计报告
     */
    @GetMapping("/statistics")
    public AjaxResult getStatisticsReport(@RequestParam(required = false) String regionCode,
                                         @RequestParam String startTime,
                                         @RequestParam String endTime)
    {
        Date start = DateUtils.parseDate(startTime);
        Date end = DateUtils.parseDate(endTime);
        String report = sensorDataService.getSensorDataStatisticsReport(regionCode, start, end);
        return AjaxResult.success(report);
    }

    /**
     * 导出传感器数据列表
     */
    @PreAuthorize("@ss.hasPermi('sensor:data:export')")
    @Log(title = "传感器数据", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SensorData sensorData)
    {
        List<SensorData> list = sensorDataService.exportSensorData(sensorData);
        ExcelUtil<SensorData> util = new ExcelUtil<SensorData>(SensorData.class);
        util.exportExcel(response, list, "传感器数据");
    }

    /**
     * 获取传感器数据详细信息
     */
    @PreAuthorize("@ss.hasPermi('sensor:data:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(sensorDataService.selectSensorDataById(id));
    }

    /**
     * 新增传感器数据
     */
    @PreAuthorize("@ss.hasPermi('sensor:data:add')")
    @Log(title = "传感器数据", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SensorData sensorData)
    {
        return toAjax(sensorDataService.insertSensorData(sensorData));
    }

    /**
     * 批量新增传感器数据
     */
    @PreAuthorize("@ss.hasPermi('sensor:data:add')")
    @Log(title = "传感器数据批量新增", businessType = BusinessType.INSERT)
    @PostMapping("/batch")
    public AjaxResult batchInsert(@RequestBody List<SensorData> sensorDataList)
    {
        return toAjax(sensorDataService.batchInsertSensorData(sensorDataList));
    }

    /**
     * 处理实时传感器数据
     * 接收外部传感器数据进行处理和判断
     */
    @PostMapping("/realtime")
    public AjaxResult processRealtimeData(@RequestParam String regionCode,
                                         @RequestParam String sensorType,
                                         @RequestParam Double value,
                                         @RequestParam(required = false) String robotId,
                                         @RequestParam(required = false) String taskId,
                                         @RequestParam(required = false) Double coordinateX,
                                         @RequestParam(required = false) Double coordinateY,
                                         @RequestParam(required = false) Double coordinateZ)
    {
        SensorData result = sensorDataService.processRealtimeSensorData(regionCode, sensorType, value, 
                                                                        robotId, taskId, 
                                                                        coordinateX, coordinateY, coordinateZ);
        if (result != null)
        {
            return AjaxResult.success("传感器数据处理成功", result);
        }
        else
        {
            return AjaxResult.error("传感器数据处理失败");
        }
    }

    /**
     * 修改传感器数据
     */
    @PreAuthorize("@ss.hasPermi('sensor:data:edit')")
    @Log(title = "传感器数据", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SensorData sensorData)
    {
        return toAjax(sensorDataService.updateSensorData(sensorData));
    }

    /**
     * 更新传感器数据处理状态
     */
    @PreAuthorize("@ss.hasPermi('sensor:data:edit')")
    @Log(title = "传感器数据处理状态", businessType = BusinessType.UPDATE)
    @PutMapping("/handle")
    public AjaxResult updateHandleStatus(@RequestParam Long id,
                                        @RequestParam String handleStatus,
                                        @RequestParam(required = false) String handleRemark)
    {
        return toAjax(sensorDataService.updateSensorDataHandleStatus(id, handleStatus, getUsername(), handleRemark));
    }

    /**
     * 批量更新传感器数据处理状态
     */
    @PreAuthorize("@ss.hasPermi('sensor:data:edit')")
    @Log(title = "传感器数据批量处理", businessType = BusinessType.UPDATE)
    @PutMapping("/batchHandle")
    public AjaxResult batchUpdateHandleStatus(@RequestParam Long[] ids,
                                             @RequestParam String handleStatus,
                                             @RequestParam(required = false) String handleRemark)
    {
        return toAjax(sensorDataService.batchUpdateSensorDataHandleStatus(ids, handleStatus, getUsername(), handleRemark));
    }

    /**
     * 删除传感器数据
     */
    @PreAuthorize("@ss.hasPermi('sensor:data:remove')")
    @Log(title = "传感器数据", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(sensorDataService.deleteSensorDataByIds(ids));
    }

    /**
     * 根据时间范围删除传感器数据
     */
    @PreAuthorize("@ss.hasPermi('sensor:data:remove')")
    @Log(title = "传感器数据时间清理", businessType = BusinessType.DELETE)
    @DeleteMapping("/time")
    public AjaxResult deleteByTime(@RequestParam String beforeTime)
    {
        Date time = DateUtils.parseDate(beforeTime);
        return toAjax(sensorDataService.deleteSensorDataByTime(time));
    }

    /**
     * 清理历史传感器数据（保留最近N天的数据）
     */
    @PreAuthorize("@ss.hasPermi('sensor:data:remove')")
    @Log(title = "传感器数据历史清理", businessType = BusinessType.DELETE)
    @DeleteMapping("/clean")
    public AjaxResult cleanHistoryData(@RequestParam(defaultValue = "30") Integer keepDays)
    {
        return toAjax(sensorDataService.cleanHistorySensorData(keepDays));
    }
}